package com.zxl.yjb.fragment.near;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.zxl.yjb.R;
import com.zxl.yjb.adapter.HorizontalImageAdapter;
import com.zxl.yjb.base.LazyBaseFragment;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.voiceplayer.EaseChatRowVoicePlayer;
import com.zxl.yjb.widget.EaseVoiceRecorderView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

public class MultifunctionalInputFragment extends LazyBaseFragment implements View.OnTouchListener {
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.ll_record)
    LinearLayout llRecord;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.ll_play)
    LinearLayout llPlay;
    @BindView(R.id.iv_add_pic)
    ImageView ivAddPic;
    @BindView(R.id.iv_camera)
    ImageView ivCamera;
    @BindView(R.id.recycler_pic_list)
    RecyclerView recyclerPicList;
    @BindView(R.id.btn_submit)
    public Button btnSubmit;
    @BindView(R.id.ll_add_pic)
    LinearLayout llAddPic;
    @BindView(R.id.rl_voice)
    RelativeLayout rlVoice;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    @BindView(R.id.tv_reRecord)
    TextView tv_reRecord;

    private List<LocalMedia> selectList = new ArrayList<>();//选择图片路径
    private HorizontalImageAdapter adapter;
    private String voiceFilePath = ""; //录音文件路径
    EaseVoiceRecorderView voiceRecorderView;
    private OnInputCompleteListener onInputCompleteListener;
    private Disposable mDisposable;
    private long voiceTimeLength;

    @Override
    protected int getLayoutId() {
        return R.layout.multifunction_input_layout;
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerPicList.setLayoutManager(manager);
        HorizontalImageAdapter.onAddPicClickListener onAddPicClickListener = new HorizontalImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick(View view) {
                DisplayUtil.openAlbum(getActivity(), 8, selectList, PictureConfig.CHOOSE_REQUEST);
            }
        };
        adapter = new HorizontalImageAdapter(getContext(), onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(8);
        recyclerPicList.setAdapter(adapter);
    }

    @Override
    protected void initEvent() {
        llRecord.setOnTouchListener(this);//开始录音
    }

    @OnClick({R.id.iv_voice, R.id.iv_add, R.id.ll_play, R.id.iv_add_pic, R.id.iv_camera, R.id.btn_submit,R.id.tv_reRecord})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_voice://显示录音
                rlVoice.setVisibility(View.VISIBLE);
                llAddPic.setVisibility(View.GONE);
                recyclerPicList.setVisibility(View.GONE);
                break;
            case R.id.iv_add://显示选择图片或拍照
                rlVoice.setVisibility(View.GONE);
                llAddPic.setVisibility(View.VISIBLE);
                recyclerPicList.setVisibility(View.GONE);
                break;

            case R.id.ll_play://开始播放
                playVoice();
                break;
            case R.id.iv_add_pic://添加图片+号
                DisplayUtil.openAlbum(getActivity(), 8, selectList, PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.iv_camera://打开相机

                break;
            case R.id.btn_submit://发布，让activity执行
                if (onInputCompleteListener != null)
                    onInputCompleteListener.onSubmitButtonClick(etInput.getText().toString(), selectList, voiceFilePath);
                break;
            case R.id.tv_reRecord:
                voiceFilePath = "";
                llRecord.setVisibility(View.VISIBLE);
                llPlay.setVisibility(View.GONE);
                break;
        }
    }

    /*获取输入框*/
    public EditText getEdittext()
    {
        return etInput;
    }

    /**
     * 绑定一个手势滑动时改变的控件
     *
     * @param voiceRecorderView
     */

    public void bindVoiceRecorderView(EaseVoiceRecorderView voiceRecorderView) {
        this.voiceRecorderView = voiceRecorderView;
    }

    /**
     * 播放录音
     */
    private void playVoice() {
        File file = new File(voiceFilePath);
        if (file.exists() && file.isFile()) {
            EaseChatRowVoicePlayer voicePlayer = EaseChatRowVoicePlayer.getInstance(getActivity());
            if (mDisposable != null) {
                mDisposable.dispose();
            }
            countDown(voiceTimeLength/1000);
            voicePlayer.play(voiceFilePath, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    // Stop the voice play animation.
//                ((EaseChatRowVoice) getChatRow()).stopVoicePlayAnimation();
                }
            });
        }
    }

    @Override
    public boolean onTouch(final View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.ll_record://录音
                if (voiceRecorderView != null)

                    return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderView.EaseVoiceRecorderCallback() {
                        @Override
                        public void onVoiceRecordComplete(String voiceFilePath, long voiceTimeLength) {
//                        sendVoiceMessage(voiceFilePath, voiceTimeLength);
                            MultifunctionalInputFragment.this.voiceTimeLength = voiceTimeLength;
                            MultifunctionalInputFragment.this.voiceFilePath = voiceFilePath;
                            tvCountDown.setText(voiceTimeLength / 1000+"秒");
                            //录音完成InputVoiceFragment
                            llRecord.setVisibility(View.GONE);
                            llPlay.setVisibility(View.VISIBLE);
                        }
                    });
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST: // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    //刷新图片列表；
                    rlVoice.setVisibility(View.GONE);
                    llAddPic.setVisibility(View.GONE);
                    recyclerPicList.setVisibility(View.VISIBLE);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    public void clearMsg() {
        voiceFilePath = "";
        selectList.clear();
        adapter.notifyDataSetChanged();
        etInput.getText().clear();
    }

    /**
     * 用这个接口将提交发布的任务交给activity处理
     */

    public interface OnInputCompleteListener {
        void onSubmitButtonClick(String content, List<LocalMedia> imgPath, String voiceFilePath);
    }

    public void setOnInputViewItemClickListener(OnInputCompleteListener onInputCompleteListener) {
        this.onInputCompleteListener = onInputCompleteListener;
    }

    /**
     * 倒计时
     * @param count
     */
    public void countDown(final long count) {

        // 倒计时 10s
        mDisposable = Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        tvCountDown.setText( String.valueOf(count - aLong) );
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                    //结束
                    }
                })
                .subscribe();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
}
